package com.axend.lib_base.help.otgserial;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;

/**
 * radar data send
 */
public class DataSender {

    public enum TvtMessageTcpFuncE {
        Tvt_Msg_Tcp_Fuc_Set_heart_startFreq_Hz(0x041B),
        Tvt_Msg_Tcp_Fuc_Get_heart_startFreq_Hz(0x041C),
        Tvt_Msg_Tcp_Fuc_Set_heart_endFreq_Hz(0x041D),
        Tvt_Msg_Tcp_Fuc_Get_heart_endFreq_Hz(0x041E);

        private final int value;

        TvtMessageTcpFuncE(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }
    }

    public static byte[] getSendData(TvtMessageTcpFuncE func, byte[] sendData) {
        List<Byte> header = new ArrayList<>();

        byte[] bFunc = ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN).putShort((short) func.getValue()).array();

        byte[] sendBuffer = new byte[]{
            0x13, 0x01, 0x00, 0x02, (byte) 0x9B,
            0x00, 0x00, 0x00, 0x10, 0x27,
            0x06, 0x00, 0x00, 0x00
        };
//        byte[] sendBuffer = new byte[]{0x13, 0x01, 0x00, 0x02, 0x00,
//                0x00, 0x0E, (byte) 0x87, 0x00, 0x00,
//                0x00, 0x00, 0x00, 0x06, 0x00};

        byte[] zeroData = new byte[]{0x00, 0x00, 0x00, 0x00};

        if (sendData == null) {
            byte[] contentLen = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(zeroData.length + 2).array();
            System.arraycopy(contentLen, 0, sendBuffer, 10, 4);
            header.addAll(toByteList(sendBuffer));
            header.addAll(toByteList(bFunc));
            header.addAll(toByteList(zeroData));
        } else {
            byte[] contentLen = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(sendData.length + 2).array();
            System.arraycopy(contentLen, 0, sendBuffer, 10, 4);
            header.addAll(toByteList(sendBuffer));
            header.addAll(toByteList(bFunc));
            header.addAll(toByteList(sendData));
        }

        return toByteArray(header);
    }

    private static List<Byte> toByteList(byte[] array) {
        List<Byte> list = new ArrayList<>();
        for (byte b : array) {
            list.add(b);
        }
        return list;
    }

    private static byte[] toByteArray(List<Byte> list) {
        byte[] array = new byte[list.size()];
        for (int i = 0; i < list.size(); i++) {
            array[i] = list.get(i);
        }
        return array;
    }

    private static void reverseBytes(byte[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            byte temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }
    }
}
